package com.yuyh.library.uis.activitys;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.View;

import com.yuyh.library.R;
import com.yuyh.library.mvp.presenters.BasePresenter;
import com.yuyh.library.mvp.views.IBaseView;
import com.yuyh.library.utils.Utils;

import java.util.Locale;

import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import io.reactivex.subjects.BehaviorSubject;

/**
 * created by arvin on 16/10/24 14:55
 * email：1035407623@qq.com
 */
public abstract class BaseActivity extends AppCompatActivity implements IBaseView {

    private BasePresenter mPresenter;
    protected ProgressDialog progressDialog;
    private BehaviorSubject<Boolean> isDestroyBehaviorSubject = BehaviorSubject.create();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setMyLanguage();
        super.onCreate(savedInstanceState);
        setContentView(getContentViewId());
        ButterKnife.bind(this);
        mPresenter = new BasePresenter(this);
        init(savedInstanceState);
        isDestroyBehaviorSubject.onNext(false);
    }

    private void setMyLanguage() {
        String language = Utils.saveLanguage(BaseActivity.this, "", 2);
        Locale myLocale = new Locale(Locale.getDefault().getLanguage());
        if ("1".equals(language)) {
            myLocale = Locale.SIMPLIFIED_CHINESE;
        } else if ("2".equals(language)) {
            myLocale = Locale.TRADITIONAL_CHINESE;
        } else if ("3".equals(language)) {
            myLocale = Locale.ENGLISH;
        } else if ("4".equals(language)) {
            myLocale = Locale.JAPANESE;
        } else if ("5".equals(language)) {
            myLocale = Locale.KOREAN;
        }

        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);

    }

    public void showProgress(String message) {
        showProgress(message, true);
    }

    public void showProgressMy(String message) {
        showProgress(message, false);
    }

    public void showProgress(String message, boolean iscancel) {
        if (progressDialog != null) {
            if (progressDialog.isShowing()) {
                return;
            }
            progressDialog.setMessage(message != null ? message
                    : "loading...");
            progressDialog.show();
        } else {
            progressDialog = new ProgressDialog(BaseActivity.this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(iscancel);
            progressDialog.setMessage(message != null ? message
                    : "loading...");
            progressDialog.show();
        }
    }

    public void hideProgress() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    @Override
    public final <T extends View> T getView(int id) {
        return mPresenter.getView(id);
    }

    @Override
    public void showToast(String message) {

        mPresenter.showToast(message);
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void startActivity(Class clazz) {
//        mPresenter.startActivity(clazz, null, true);
        mPresenter.startActivity(clazz, null, false);//由于vivo的页面切换不友好，这里舍弃
    }

    @Override
    public void startActivity(Class clazz, Bundle bundle) {
//        mPresenter.startActivity(clazz, bundle, true);
        mPresenter.startActivity(clazz, bundle, false);//由于vivo的页面切换不友好，这里舍弃
    }

    @Override
    public void startActivity(Class clazz, boolean isAnim) {
//        mPresenter.startActivity(clazz, null, isAnim);
        mPresenter.startActivity(clazz, null, false);//由于vivo的页面切换不友好，这里舍弃
    }

    @Override
    public void startActivity(Class clazz, Bundle bundle, boolean isAnim) {
//        mPresenter.startActivity(clazz, bundle, isAnim);
        mPresenter.startActivity(clazz, bundle, false);//由于vivo的页面切换不友好，这里舍弃
    }

    @Override
    public void startActivityForResult(Class clazz, int requestCode) {
        mPresenter.startActivityForResult(clazz, requestCode, null);
    }

    @Override
    public void startActivityForResult(Class clazz, int requestCode, Bundle bundle) {
        mPresenter.startActivityForResult(clazz, requestCode, bundle);
    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(0, R.anim.af_right_out);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        isDestroyBehaviorSubject.onNext(true);
    }

    @Override
    public abstract int getContentViewId();

    @Override
    public abstract void init(Bundle savedInstanceState);

    public <T> ObservableTransformer<T, T> bindLifeCycle() {

        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                return upstream.takeUntil(isDestroyBehaviorSubject.filter(new Predicate<Boolean>() {
                    @Override
                    public boolean test(Boolean aBoolean) {
                        return aBoolean;
                    }
                }));
            }
        };
    }

    public <T> ObservableTransformer<T, T> applyProgress(final String message) {

        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                return upstream.doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(final Disposable disposable) throws Exception {
                        showProgress(message);
                        final Dialog dialog = progressDialog;
                        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                disposable.dispose();
                            }
                        });
                    }
                }).doOnError(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                    }
                }).doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        hideProgress();
                    }
                });
            }
        };
    }
}
